package com.kang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kang.entity.Label;
import com.kang.entity.SysUser;
import com.kang.mapper.LabelMapper;
import com.kang.mapper.SysUserMapper;
import com.kang.service.LabelService;
import com.kang.util.LabelHelper;
import com.kang.util.TokenToUserId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@Service
public class LabelServiceImpl extends ServiceImpl<LabelMapper, Label> implements LabelService{

    @Autowired
    private SysUserMapper sysUserMapper;

    @Override
    public List<Label> findNodes() {
        List<Label> labels = baseMapper.selectList(null);
        labels.forEach(v -> {
            SysUser user = sysUserMapper.selectById(v.getUserId());
            v.setUsername(user.getUsername());
        });
        return LabelHelper.buildTree(labels);
    }

    @Override
    public Label findLabelById(Integer id) {
        return baseMapper.selectById(id);
    }

    @Override
    public Integer insertLabel(Label label, HttpServletRequest request) throws Exception {
        label.setLabelType(5);
        label.setCreateTime(new Date());
        label.setUpdateTime(new Date());
        Integer id = TokenToUserId.TokenGetUserId(request.getHeader("token"));
        label.setUserId(id);
        label.setCreateUserId(id);
        return baseMapper.insert(label);
    }

    @Override
    public Integer deleteLabel(Integer id) {
        return baseMapper.deleteById(id);
    }

    @Override
    public Integer updateLabel(Label label, HttpServletRequest request) throws Exception {
        Integer id = TokenToUserId.TokenGetUserId(request.getHeader("token"));
        label.setUserId(id);
        label.setUpdateTime(new Date());
        return baseMapper.updateById(label);
    }

    @Override
    public List<Label> getLabelByType(Integer type) {
        QueryWrapper<Label> wrapper = new QueryWrapper<>();
        wrapper.eq("parent_id",type);
        return baseMapper.selectList(wrapper);
    }
}
